require 'encoding_conv'
require 'rexml/document'

class DummyScraper
  STRING_FILE_NAME = 'dummy_scraper_strings.xml'
  def initialize
    @count = 0
    temp_file_name = 'count.txt'
    File.open(temp_file_name) do |f|
      @count = f.readline.to_i
    end if File.exist? 'count.txt'
    
    File.open(temp_file_name, 'w') do |f|
      f.puts @count + 1
    end    
    
    begin
      @xml = REXML::Document.new(File.open(STRING_FILE_NAME))
    rescue Errno::ENOENT
      @xml = nil
    end
  end
  
  def text(xpath, *values)
    @xml.nil? ? "#{STRING_FILE_NAME} not found." : sprintf(@xml.elements[xpath].text, *values)
  end
  
  def scrape_courses(username, password)
    #~ sleep(3)
    if password == "wrong"
      return "wrong_password"
    end
    
    course = {}
    course[:name] = text("//course/name", username)
    course[:notices] = []
    course[:materials] = []
    course[:homeworks] = []
    for i in 0 ... @count
      course[:notices] << {
        :title => text("//notice/title", username, i),
        :date => text("//date", i),
        :body => text("//notice/body", username, course[:name]),
      }
      course[:materials] << {
        :title => text("//material/title", username, i),
        :description => text("//material/description", username),
        :date => text("//date", i),
      }
      course[:homeworks] << {
        :title => text("//homework/title", username, i),
        :deadline => text("//date", i),
        :date => text("//date", i),
        :handed => i % 3 == 0,
        :overdue => i % 2 == 0,
      }
    end
    [course]
  end
  
  def scrape_anycompany_mail(username, password)
    mails = []
    for i in 0 ... @count
      mails << {
        :title => text("//mail/title", username, i),
        :from => text("//mail/from"),
        :date => text("//date", i),
        :body => text("//mail/body"),
        :read => i % 3 == 0,
      }
    end
    mails
  end
  
  def scrape_mailboxes(mailbox_accounts)
    #~ sleep(3)
    mailboxes = []
    mailbox_accounts.each do |mailbox_account| 
      mailboxes << {
        :username => Iconv.conv("UTF-8", "GBK", mailbox_account[:username]),
        :type => Iconv.conv("UTF-8", "GBK", mailbox_account[:type]),
        :state => case mailbox_account[:password] 
                      when "suspend"
                        "suspended"
                      when "wrong"
                        "wrong_password"
                      else
                        "ok"
                      end,
        :mails => scrape_anycompany_mail(mailbox_account[:username], mailbox_account[:password])
      }
    end
    mailboxes
  end
  
end

